package com.funcourse.demo.aliyun.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.TagSet;
import com.funcourse.demo.business.RedisResourceLock;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class ObjectTagger {

  private static final String OBJECT_LOCK_KEY_PREFIX="funcourse.lock.oss.object.";
  private static final String OBJECT_REFER_TAG="refer";
  @Autowired
  RedisTemplate redisTemplate;
  @Autowired
  OssConfig ossConfig;
  RedisResourceLock redisResourceLock;

  public void increaseOrInitReferenceTag(int count,String objectName){
    redisResourceLock.tryToGetResourceLockBlocking(objectName);
    final OSS ossClient = ossConfig.getOssClient();
    final String bucketName = ossConfig.getBucketName();
    TagSet objectTagging = ossClient
        .getObjectTagging(bucketName, objectName);
    if(null == objectTagging){
      objectTagging = new TagSet();
      objectTagging.setTag(OBJECT_REFER_TAG,String.valueOf(count));
    }else{// objectTagging is not null
      final String tagValue = objectTagging.getTag(OBJECT_REFER_TAG);
      if(null == tagValue){
        objectTagging.setTag(OBJECT_REFER_TAG,String.valueOf(count));
      }else{
        try{
          int tagReferenceCount = Integer.parseInt(tagValue);
          tagReferenceCount += count;
          if(tagReferenceCount<0){
            tagReferenceCount = 0;
          }
          objectTagging.setTag(OBJECT_REFER_TAG,String.valueOf(tagReferenceCount));
        }catch (Exception e){//tag value not integer
          objectTagging.setTag(OBJECT_REFER_TAG,String.valueOf(count));
        }
      }
    }
    ossClient.setObjectTagging(bucketName,objectName,objectTagging);
    redisResourceLock.releaseResourceLock(objectName);
  }


  @PostConstruct
  public void initRedisResourceLock(){
    redisResourceLock = new RedisResourceLock(OBJECT_LOCK_KEY_PREFIX,redisTemplate);
  }

}
